<template>
  <div class="app-container">
    <!-- 条件栏 -->
    <div class="filter-wrapper">
      <NewPageFilter
        ref="pageFilter"
        v-model:query="filterInfo.query.queryMap"
        :query-more-json="true"
        :filter-list="filterInfo.searchList"
        :filter-btn="filterInfo.searchBtn"
        :clear-type="clearType"
        :slip-select-request="slipSelectRequest"
      >
      </NewPageFilter>
    </div>

    <div class="filter-wrapper">
      <NewPageFilter :filter-btn="filterInfo.btnList">
        <template v-slot:filter-excel>
          <el-button :disabled="groupFlag" @click="exportExcel()"
            >导出excel</el-button
          >
        </template>
      </NewPageFilter>
      <div class="display-flex">
        <Group-select
          :options="groupSelectInfo.options"
          v-model:selections="groupSelectInfo.selections"
          @callback="groupSelect"
          @callbackVal="updateGroupSelections"
        ></Group-select>
        <el-button @click="preferenceInfo.visible = true">偏好设置</el-button>
      </div>
    </div>
    <!-- 表格 -->
    <TableContainer
      v-if="groupFlag"
      class="groupFlag-container"
      :check-box="false"
      v-model:data="groupSelectInfo.data"
      :field-list="tableInfo.fieldList"
      :is-group-search="true"
      :pager="false"
      :row-class-name="tableRowClassName"
      :span-method="arraySpanMethod"
      :tab-index="false"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      @exChange="exChange"
      @handleEvent="handleEvent"
      @sortChange="sortChange"
    >
    </TableContainer>
    <!-- 表格 -->
    <TableContainer
      v-else
      :refresh="tableInfo.refresh"
      :init-curpage="tableInfo.initCurpage"
      v-model:data="tableInfo.data"
      :api="tableInfo.api"
      :tab-index="true"
      :check-box="false"
      :query="filterInfo.query"
      :field-list="tableInfo.fieldList"
      @handleEvent="handleEvent"
    >
    </TableContainer>
    <SetPreference
      v-if="preferenceInfo.visible"
      v-model:visible="preferenceInfo.visible"
      :search-list="filterInfo.searchList"
      :field-list="tableInfo.fieldList"
      :customize-user-v-o="filterInfo.query.customizeUserVO"
      @callback="setPreferenceCallback"
    />
    <AdvancedSearch
      v-if="advancedSearchInfo.visible"
      v-model:visible="advancedSearchInfo.visible"
      :field-list="tableInfo.fieldList"
      v-model:form-data="advancedSearchInfo.data"
      @callback="advancedSearchCallback"
    />
    <PageDialog
      v-show="dialogInfo.visible"
      :title="dialogInfo.title"
      v-model:visible="dialogInfo.visible"
      :width="dialogInfo.width"
      :bt-loading="dialogInfo.btLoading"
      :bt-list="dialogInfo.btList"
    >
      <div class="asset-msg">
        <div class="asset-msg-label">
          <i class="el-icon-warning"></i>{{ dialogInfo.msg }}：
        </div>
        <el-radio-group v-model="dialogInfo.flag">
          <el-radio :label="true">当前页数据</el-radio>
          <el-radio :label="false">全部页数据</el-radio>
        </el-radio-group>
      </div>
    </PageDialog>
  </div>
</template>

<script setup name="consignmentMaterial">
import {
  getMaterialCustomizeListPage,
  getMaterialCustomizeAll,
  getMaterialCustomizeGroups,
  exportConsignmentMaterialExcel,
} from '@/api/fiscal.js'
import { getCustomizeSetting, updateUserCustomize } from '@/api/customize'
import { ElMessage } from 'element-plus'
import utils from '@/common/js/utils'

const { proxy } = getCurrentInstance()

//导出提示相关配置
const dialogInfo = reactive({
  visible: false,
  title: '提示',
  btLoading: false,
  type: '',
  msg: '',
  width: '400px',
  flag: true,
  btList: [
    { label: '关闭', event: handleClose, show: true },
    {
      label: '打印',
      type: 'primary',
      event: checkConfirm,
      show: true,
    },
  ],
})
// 过滤相关配置
const groupSelectInfo = reactive({
  options: [],
  selections: [],
  data: [],
})
const filterInfo = reactive({
  query: {
    groupMap: {},
    groups: [],
    sortString: '',
    customizeUserVO: {},
    queryMap: {
      isConsignBusiness: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: 1,
      },
    },
  },
  searchList: [],
  searchBtn: [
    { type: 'button', label: '搜索', event: search },
    { type: 'button', label: '高级查询', event: advancedSearchShow },
    { type: 'button', label: '重置', event: clearSearch },
  ],
  btnList: [
    {
      value: 'excel',
      type: 'slot',
    },
  ],
})

const tableInfo = reactive({
  refresh: 1,
  initCurpage: 1,
  data: [],
  api: undefined,
  selections: [],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '100',
    btList: [],
  },
})
const preferenceInfo = reactive({
  visible: false,
})

const advancedSearchInfo = reactive({
  visible: false,
  data: {},
})
const page = ref({
  page: true,
  curPage: 1, // 当前页
  pageSize: 20, // 每页条数
})
const operateTime = ref(null)
const clearType = ref(true)
const slipSelectRequest = ref(true)
const groupFlag = ref(false)

let obj = {
  fiscalPeriodName: {
    label: '会计期间',
    value: 'fiscalPeriodName',
    componentType: 'input',
    show: false,
    hidden: true,
  },
  beforeQty: {
    label: '期初数量',
    value: 'beforeQty',
    type: 'column',
    componentType: 'number',
    formatter: utils.qtyFormatter,
    show: false,
    hidden: true,
  },
  beforeAmount: {
    label: '期初金额',
    value: 'beforeAmount',
    type: 'column',
    componentType: 'number',
    formatter: utils.TripartiteMethod,
    show: false,
    hidden: true,
  },
  storeQty: {
    label: '入库数量',
    value: 'storeQty',
    type: 'column',
    componentType: 'number',
    formatter: utils.qtyFormatter,
    show: false,
    hidden: true,
  },
  storeAmount: {
    label: '入库金额',
    value: 'storeAmount',
    type: 'column',
    componentType: 'number',
    formatter: utils.TripartiteMethod,
    show: false,
    hidden: true,
  },
  exportQty: {
    label: '出库数量',
    value: 'exportQty',
    type: 'column',
    componentType: 'number',
    formatter: utils.qtyFormatter,
    show: false,
    hidden: true,
  },
  exportAmount: {
    label: '出库金额',
    value: 'exportAmount',
    type: 'column',
    componentType: 'number',
    formatter: utils.TripartiteMethod,
    show: false,
    hidden: true,
  },
  endQty: {
    label: '期末数量',
    value: 'endQty',
    type: 'column',
    componentType: 'number',
    formatter: utils.qtyFormatter,
    show: false,
    hidden: true,
  },
  endAmount: {
    label: '期末金额',
    value: 'endAmount',
    type: 'column',
    componentType: 'number',
    formatter: utils.TripartiteMethod,
    show: false,
    hidden: true,
  },
  fiscalPeriodName: {
    label: '会计期间',
    value: 'fiscalPeriodName',
    asValue: 'fiscalPeriodName',
    componentType: 'select-fiscal-period',
    query: {
      fiscalType: 1,
    }, //1 = 物资 2 = 资产
    highlightRow: true,
    checkBox: false,
    show: false,
    hidden: true,
  },
}
tableInfo.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
})
filterInfo.searchList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
  commonName: {
    label: '通用名称',
    value: 'commonName',
    componentType: 'input',
    show: false,
    hidden: true,
  },
})
getCustomize()

function updateGroupSelections(arr) {
  filterInfo.query.groups = arr
  groupSelectInfo.selections = arr
  if (!arr.length) {
    filterInfo.query.groups = []
    filterInfo.query.groupMap = {}
    groupSelectInfo.data = []
    groupFlag.value = false
  }
}
function groupSelect(arr) {
  if (arr.length) {
    //点击分组
    groupFlag.value = true
    filterInfo.query.groups = arr
    groupSelectInfo.selections = arr
    getCustomizeGroupsList()
  } else {
    ElMessage.warning({
      message: '请选择分组条件！',
      showClose: true,
      duration: 3000,
    })
  }
}
async function getCustomizeGroupsList(len, param, expande) {
  //分组查询
  let params = {}
  if (len) {
    params = param
  } else {
    params = filterInfo.query
  }
  if (filterInfo.query.queryDtoList && filterInfo.query.queryDtoList.length) {
    params = proxy.$fn.deepClone(params)
    params.queryMap = {}
  }
  await getMaterialCustomizeGroups(params).then(async (res) => {
    if (res && res.success) {
      let data = res.data
      let newData = []
      if (len) {
        await data.forEach((item, index) => {
          newData.push({
            ...item,
            id: index + Math.random(),
            isColspan: true,
            children: [{ ...item, id: index + Math.random(), isColspan: true }],
          })
        })
        expande.children = newData
      } else {
        await data.forEach((item, index) => {
          newData.push({
            ...item,
            id: index + Math.random(),
            isColspan: true,
            children: [{ id: index + Math.random(), isColspan: true }],
          })
        })
        groupSelectInfo.data = newData
      }
    }
  })
}
function exChange(data, expandedRows) {
  //展开分组
  if (expandedRows) {
    let len = data.nextGroups.length
    if (len) {
      let params = {
        ...filterInfo.query,
        groups: data.nextGroups,
        groupMap: { ...data.query },
        queryMap: { ...filterInfo.query.queryMap, ...data.query },
      }
      getCustomizeGroupsList(len, params, data)
    } else {
      let params = {
        ...filterInfo.query,
        groups: [],
        groupMap: {},
        queryMap: { ...filterInfo.query.queryMap, ...data.query },
      }
      getMaterialCustomizeAll(params).then(async (res) => {
        if (res && res.success) {
          let resData = res.data
          await resData.forEach((item, index) => {
            item.id = index + Math.random()
            item.isColspan = false
          })
          data.children = resData
        }
      })
    }
  } else {
    data.children = [{ id: Math.random(), isColspan: true }]
  }
}

function setPreferenceCallback(obj) {
  updateUserCustomize(obj.customizeUserVO).then((res) => {
    if (res && res.success) {
      getCustomize(!slipSelectRequest.value)
    }
  })
}
function advancedSearchShow() {
  advancedSearchInfo.visible = true
}
async function advancedSearchCallback(obj) {
  filterInfo.query.queryMap = {}
  filterInfo.query.queryDtoList = [...obj.queryDtoList]
  advancedSearchInfo.data = obj.data
  if ((await groupSelectInfo.selections.length) > 0) {
    await getCustomizeGroupsList()
  } else {
    groupSelectInfo.data = []
    await getList()
  }
  clearType.value = !clearType.value
  filterInfo.query.queryMap = proxy.$fn.deepClone(filterInfo.copyQueryMap)
}
async function getList() {
  tableInfo.refresh = Math.random()
}
function search() {
  advancedSearchInfo.data = {}
  filterInfo.query.queryDtoList = []
  if (groupSelectInfo.selections.length > 0) {
    getCustomizeGroupsList()
  } else {
    groupSelectInfo.data = []
    tableInfo.initCurpage = Math.random()
    tableInfo.refresh = Math.random()
  }
}
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.selections = [...data]
      break
  }
}
function clearSearch() {
  clearType.value = !clearType.value
  filterInfo.query.queryMap = proxy.$fn.deepClone(filterInfo.copyQueryMap)
  operateTime.value = null
  search()
}
function getCustomize(_slipSelectRequest = true) {
  let param = {
    tableKey:
      'consignmentMaterialMonthCloseList-com.slip.spd.entity.vo.fiscal.FiscalPeriodStockMonthCloseVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.query.customizeUserVO = data
      let searchInfo = proxy.$fn.setSearchList(
        filterInfo.searchList,
        data.detail
      )
      let tableFieldInfo = proxy.$fn.setFieldList(
        tableInfo.fieldList,
        data.detail,
        true
      )

      tableInfo.fieldList = tableFieldInfo.fieldList
      groupSelectInfo.options = tableFieldInfo.groupOption
      filterInfo.query.queryMap = {
        ...searchInfo.queryMap,
        ...filterInfo.query.queryMap,
      }
      filterInfo.copyQueryMap = proxy.$fn.deepClone(filterInfo.query.queryMap)
      filterInfo.searchList = searchInfo.searchList
      filterInfo.searchList.forEach((item) => {
        item.event = search
      })

      slipSelectRequest.value = _slipSelectRequest
      tableInfo.api = getMaterialCustomizeListPage
      getList()
    }
  })
}
function sortChange(column) {
  if (filterInfo.query.customizeUserVO.head.sortType === 0) {
    let arr = proxy.$fn.sortChange(column, filterInfo.sortArr)
    filterInfo.sortArr = arr
    filterInfo.query.sortString = arr.toString()
    getList()
  }
}
function tableRowClassName(row) {
  if (row.row.nextGroups) {
    return 'bg-color-EBEEF5'
  } else {
    return ''
  }
}
function arraySpanMethod({ row, columnIndex }) {
  if (row.nextGroups) {
    if (columnIndex === 0) {
      return {
        rowspan: 1,
        colspan: tableInfo.fieldList.length,
      }
    }
  }
}
function handleClose() {
  dialogInfo.visible = false
}
async function exportExcel() {
  dialogInfo.visible = true
  dialogInfo.type = 'excel'
  dialogInfo.msg = '请选择数据导出范围'
  dialogInfo.btList[1].label = '导出'
  dialogInfo.flag = true
}
function checkConfirm() {
  if (dialogInfo.type === 'excel') {
    exportExcelList()
  } else if (dialogInfo.type === 'print') {
    // printList()
  }
  dialogInfo.visible = false
  dialogInfo.msg = ''
}
function exportExcelList() {
  let query = {
    customizeDto: filterInfo.query,
  }
  let params = {
    ...query,
    ...page.value,
    page: dialogInfo.flag,
  }
  exportConsignmentMaterialExcel(params).then((resp) => {
    if (resp) {
      proxy.$fn.parseExcel(resp)
    }
  })
}
</script>

<style scoped></style>
